<?php

/**
 * [Discuz!] (C)2001-2099 Comsenz Inc.
 * This is NOT a freeware, use is subject to license terms
 *
 * $Id: function_shop.php 23826 22-11-2011 11:04:00 mr.Trieu $
 */

if (!defined('IN_DISCUZ')){
	exit('Access Denied');
}

function shop_menu($sid = 0, $showhide = FALSE, $evalue = FALSE){
	global $_G;

	if (!isset($_G['cache']['shops'])){
		loadcache('shops');
	}
	$shopcache = &$_G['cache']['shops'];
	$shoplist = array();
	$new_menu = array();

	if (!$sid){
		foreach ($shopcache as $shop_category){

			if (!$shop_category['status'] && !$showhide){
				continue;
			}

			if ($shop_category['type'] == 'group'){

				$shoplist[$shop_category['sid']]['name'] = $shop_category['name'];
				$visible[$shop_category['sid']] = true;

			}elseif ($shop_category['type'] == 'shop' && isset($visible[$shop_category['sup']]) && (!$shop_category['viewperm'] || ($shop_category['viewperm'] && forumperm($shop_category['viewperm'])) || strstr($shop_category['users'], "\t$_G[uid]\t"))){
				$shoplist[$shop_category['sup']]['sub'][$shop_category['sid']]['name'] = $shop_category['name'];
				$parent_shop[$shop_category['sid']]['parent'] = $shop_category['sup'];
				$visible[$shop_category['sid']] = true;

			}elseif ($shop_category['type'] == 'sub' && isset($visible[$shop_category['sup']]) && (!$shop_category['viewperm'] || ($shop_category['viewperm'] && forumperm($shop_category['viewperm'])) || strstr($shop_category['users'], "\t$_G[uid]\t"))){
				$shoplist[$parent_shop[$shop_category['sup']]['parent']]['sub'][$shop_category['sup']]['sub'][$shop_category['sid']]['name'] = $shop_category['name'];

			}
		}
		return $shoplist;
	}else{
		$sub = array();
		foreach ($shopcache as $category){
			if (!$category['status'] && !$showhide){
				continue;
			}
			if ($sid == $category['sup']){
				$new_menu[$category['sid']]['name'] = $category['name'];
				$sub[] = $category['sid'];
			}
			if (in_array($category['sup'], $sub)){
				$new_menu[$category['sup']]['sub'] = 'yes';
			}
		}
		return $new_menu;
	}
}

function loadshop(){
	global $_G;
	//Lay product id va shop category id
	$pid = intval($_G['gp_pid']);
	$sid = intval($_G['gp_sid']);

	if ($sid){
		$sid = is_numeric($sid) ? intval($sid) : (!empty($_G['setting']['shopsids'][$sid]) ? $_G['setting']['shopsids'][$sid] : 0);
	}

	//khoi tao kich thuoc cho anh thumb
	if ($_G['setting']['shoppicstyle']){
		$_G['setting']['shoppicstyle'] = unserialize($_G['setting']['shoppicstyle']);
		empty($_G['setting']['shoppicstyle']['thumbwidth']) && $_G['setting']['shoppicstyle']['thumbwidth'] = 214;
		empty($_G['setting']['shoppicstyle']['thumbheight']) && $_G['setting']['shoppicstyle']['thumbheight'] = 160;
	}else{
		$_G['setting']['shoppicstyle'] = array(
				'thumbwidth'=>214,
				'thumbheight'=>160
		);
	}

	$accessadd1 = $accessadd2 = $modadd1 = $modadd2 = $metadescription = '';
	$adminid = $_G['adminid'];

	if ($_G['uid']){
		if ($_G['member']['accessmasks']){
			$accessadd1 = ', a.allowview, a.allowpost, a.allowreply, a.allowgetattach, a.allowgetimage, a.allowpostattach, a.allowpostimage';
			$accessadd2 = "LEFT JOIN " . DB::table('shop_access') . " a ON a.uid='$_G[uid]' AND a.sid=s.sid";
		}

		if ($adminid == 3){
			$modadd1 = ', m.uid AS ismoderator';
			$modadd2 = "LEFT JOIN " . DB::table('shop_moderator') . " m ON m.uid='$_G[uid]' AND m.sid=s.sid";
		}
	}

	$product = '';
	if (!empty($pid) || !empty($sid)){
		if ($pid){
			$product = DB::fetch_first("SELECT p.*, d.name as province , m.*
											FROM " . DB::table('shop_products') . " p
											LEFT JOIN " . DB::table("common_district") . " d ON p.location_province = d.id
											LEFT JOIN " . DB::table("shop_profile") . " m ON p.uid = m.uid
											WHERE p.pid = '$pid'");
			if (!$product){
				showmessage(lang('shop/tempalte', 'product_is_not_avaible'));
			}else{
				$product['tax'] = unserialize($product['tax']);
				$product['images'] = unserialize($product['images']);
			}

			$datachange = " view = view + 1 ";

			$product['view'] = $product['view'] + 1;
			DB::query("UPDATE " . DB::table('shop_products') . " SET $datachange WHERE pid = $pid");
		}

		if (!$sid && $product['cid'])
			$sid = $product['cid'];

		$shop_category = DB::fetch_first("SELECT s.*, ss.* $accessadd1 $modadd1
									FROM " . DB::table('shop_category') . " s
									LEFT JOIN " . DB::table("shop_shopfield") . " ss ON ss.sid=s.sid $accessadd2 $modadd2
									WHERE s.sid='$sid'");

		if ($shop_category){
			$shop_category['ismoderator'] = !empty($shop_category['ismoderator']) || $adminid == 1 || $adminid == 2 ? 1 : 0;
			$sid = $shop_category['sid'];

			foreach (array(
					'threadtypes',
					'threadsorts',
					'creditspolicy',
					'modrecommend',
					'param'
			) as $key){
				$shop_category[$key] = !empty($shop_category[$key]) ? unserialize($shop_category[$key]) : array();
				if (!is_array($shop_category[$key])){
					$shop_category[$key] = array();
				}
				if ($key == 'param' && $_G['gp_mod'] == 'post'){
					foreach ($shop_category['param'] as $key2=>$value){
						$shop_category['param'][$key2]['value'] = explode(chr(10), $value['value']);
					}
				}
			}
		}else
			$sid = 0;

	}

	$_G['sid'] = $sid;
	$_G['pid'] = $pid;
	$_G['shop'] = &$shop_category;
	$_G['product'] = &$product;
}

function check_profile_shop($uid){
	$profile = NULL;
	$profile = DB::fetch_first("SELECT * FROM " . DB::table("shop_profile") . " p WHERE p.uid= '" . $uid . "'");
	return $profile;
}

function list_products($condition, $paramadd = '', $accessadd = '', $start = 0, $limit = 10, &$count = '', $counter = FALSE, $formatPrice = TRUE){
	global $_G;
	$products = array();
	$condition2 = " (p.pprice > '2000' OR p.uid = '$_G[uid]') ";

	if ($_G['adminid'] != 1){
		$condition2 .= "  AND `available` = '1'";
	}

	$sql = "SELECT p.pid, p.cid, p.uid, p.view, p.username, p.pname, p.punit,p.location_province, p.pcode, p.sales, p.state, p.b_sales, p.e_sales, p.total_vote, p.vote,
			p.img_cover, p.lastupdate,p.pprice,p.summary, m.*,d.name as province, a.attachment, a.remote $paramadd
			FROM " . DB::table("shop_products") . " p
			LEFT JOIN " . DB::table("common_district") . " d ON p.location_province = d.id
			LEFT JOIN " . DB::table("shop_products_attachment") . " a ON p.img_cover = a.aid
			LEFT JOIN " . DB::table("shop_profile") . " m ON p.uid = m.uid
			$accessadd
			WHERE $condition2
			$condition
			LIMIT $start, $limit";

	//echo "<pre>$sql</pre>";


	$query = DB::query($sql);

	if ($counter){
		$count = DB::result_first("SELECT COUNT(*) $paramadd
							FROM " . DB::table("shop_products") . " p
							LEFT JOIN " . DB::table("common_district") . " d ON p.location_province = d.id
							LEFT JOIN " . DB::table("shop_products_attachment") . " a ON p.img_cover = a.aid
							LEFT JOIN " . DB::table("shop_profile") . " m ON p.uid = m.uid
							$accessadd
							WHERE $condition2
							$condition ");
	}

	while ($product = DB::fetch($query)){
		if (isset($product['tax']))
			$product['tax'] = unserialize($product['tax']);

		$product['images'] = unserialize($product['images']);
		$product['imgcover'] = ($product['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . $product['attachment'];
		$product['imgcoverthumb'] = ($product['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . substr($product['attachment'], 0, 10) . $product['img_cover'] . '.thumb.jpg';
		$product['imgcoverthumbbig'] = ($product['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . substr($product['attachment'], 0, 10) . $product['img_cover'] . '.thumb.big.jpg';
		$product['issales'] = check_sales($product);

		unset($product['img_cover']);
		unset($product['attachment']);
		unset($product['remote']);

		if (check_sales($product)){
			$product['sales_status'] = true;
			$product['end_price'] = $product['pprice'] - (($product['pprice'] * $product['sales']) / 100);
			$product['sales'] = FormatNumber($product['sales'], 2, '.', ",", FALSE);
		}else
			$product['end_price'] = $product['pprice'];

		$product['behind_tax'] = $product['tax']['used'] ? ($product['end_price'] + ($product['end_price'] * $product['tax']['tax_vat']) / 100 + ($product['end_price'] * $product['tax']['tax_import']) / 100 + ($product['end_price'] * $product['tax']['tax_other']) / 100) : $product['end_price'];

		if ($formatPrice){
			$product['save_money'] = FormatNumber($product['pprice'] - $product['end_price']);
			$product['pprice'] = FormatNumber($product['pprice']);
			$product['delivery_price'] = $product['delivery_price'] != 0 ? FormatNumber($product['delivery_price']) : lang('shop/template', 'freeship');
			$product['end_price'] = FormatNumber($product['end_price']);
		}

		// Rate products
		$product['point'] = $product['total_vote'] / $product['vote'];
		$product['point'] = round($product['point']);

		if ($product['view'] > 1000)
			$product['hits'] = round($product['view'] / 1000) . 'k';
		elseif ($product['view'] > 10000)
			$product['hits'] = round($product['view'] / 10000) . 'k';
		elseif ($product['view'] > 100000)
			$product['hits'] = round($product['view'] / 100000) . 'k';
		else
			$product['hits'] = $product['view'];

		// Tong so san pham cua shopper
		$product['items'] = shopItems($product['uid']);
		// Danh sach hinh anh cua 1 san pham
		$product['pics'] = imgProduct($product['pid'], $product['attachment']);

		$products[$product['pid']] = $product;
	}

	return $products;
}

function paserimgatt($detail){
	global $_G;

	if (preg_match_all("/\[attachimg\](\d+)\[\/attachimg\]/i", $detail, $matchaids)){
		$attachlist = $matchaids[1];
		$attachlist = implode(',', $attachlist);
		$query = DB::query("SELECT * FROM " . DB::table("shop_products_attachment") . " WHERE `aid` IN ($attachlist)");
		$attachlist = '';

		while ($attach = DB::fetch($query)){
			$attach['imgurl'] = $attach['remote'] ? $_G['setting']['ftp']['attachurl'] . 'shop/' : $_G['setting']['attachurl'] . 'shop/';
			$attach['imgurl'] = $attach['imgurl'] . $attach['attachment'];
			$attachlist[$attach['aid']] = $attach;
		}
		foreach ($attachlist as $key=>$value){
			$search = '[attachimg]' . $key . '[/attachimg]';
			$replace = reg_replace_images($value);
			$detail = str_replace($search, $replace, $detail);
		}
	}
	return $detail;
}

function reg_replace_images($attach){
	$width = '';
	if ($attach['width'] > 680){
		$width = 'width = "680px" style="cursor:pointer"  alt=" Nháº¥n Ä‘á»ƒ xem áº£nh to" title="Nháº¥n Ä‘á»ƒ xem áº£nh to"';
	}
	$string = '<img id="aimg_' . $attach['aid'] . '" src="' . $attach['imgurl'] . '" zoomfile="' . $attach['imgurl'] . '" file="' . $attach['imgurl'] . '" class="zoom" onclick="zoom(this, this.src)" ' . $width . ' inpost="1" />';
	return $string;
}

function getattacshopbypid($pid){
	$query = DB::query("SELECT * FROM " . DB::table("shop_products_attachment") . " WHERE `pid` = $pid");
	while ($attach = DB::fetch($query)){
		$attach['filenametitle'] = $attach['filename'];
		$attach['ext'] = fileext(strtolower($attach['filename']));
		if ($allowext && !in_array($attach['ext'], $allowext)){
			continue;
		}
	}
}

function getattachshop($pid, $posttime = 0, $aids = ''){
	global $_G;

	require_once libfile('function/attachment');
	$attachs = $imgattachs = array();
	$aids = $aids ? explode('|', $aids) : array();
	if ($aids){
		$aidsnew = array();
		foreach ($aids as $aid){
			if ($aid){
				$aidsnew[] = intval($aid);
			}
		}
		$aids = "aid IN (" . dimplode($aidsnew) . ") AND";
	}else{
		$aids = '';
	}
	$sqladd1 = $posttime > 0 ? "AND af.dateline>'$posttime'" : '';
	if (!empty($_G['sid']) && $_G['shop']['attachextensions']){
		$allowext = str_replace(' ', '', strtolower($_G['shop']['attachextensions']));
		$allowext = explode(',', $allowext);
	}else{
		$allowext = '';
	}
	$query = DB::query("SELECT a.*, af.*
		FROM " . DB::table('forum_attachment') . " a
		LEFT JOIN " . DB::table('forum_attachment_unused') . " af USING(aid)
		WHERE $aids (af.uid='$_G[uid]' AND a.tid='0' $sqladd1) ORDER BY a.aid DESC");
	while ($attach = DB::fetch($query)){
		$attach['filenametitle'] = $attach['filename'];
		$attach['ext'] = strtolower(fileext($attach['filename']));
		if ($allowext && !in_array($attach['ext'], $allowext)){
			continue;
		}
		getattach_row($attach, $attachs, $imgattachs);
	}
	if ($pid > 0){
		$query = DB::query("SELECT * FROM " . DB::table("shop_products_attachment") . " WHERE `pid` = $pid");
		while ($attach = DB::fetch($query)){
			$attach['filenametitle'] = $attach['filename'];
			$attach['ext'] = fileext(strtolower($attach['filename']));
			//if($allowext && !in_array($attach['ext'], $allowext)) {
			//continue;
			//}
			getattach_row($attach, $attachs, $imgattachs);
		}
	}
	return array(
			'attachs'=>$attachs,
			'imgattachs'=>$imgattachs
	);
}

function param_explode($array, $output = 'html'){
	$output = '';
	$extra_num = 0;
	foreach ($array as $key){
		$output .= param_html_output($key, $extra_num);
		$extra_num++;
	}
	return $output;
}

function param_html_output($array, $num){
	$name = 'custom_' . $num;
	$type = (isset($array['type']) ? $array['type'] : 'select');
	$output = '';
	switch ($type){
		case 'select':
		case 'checkbox':
			$output = param_out_is_checkbox($array, $name);
		break;
		case 'textarea':
		case 'input':
			$output = param_out_is_input($array, $name);
		break;
		case 'droplist':
		case 'List':
			$output = param_out_is_droplist($array, $name);
		break;
	}
	return $output;
}

function param_out_is_input($array, $name = ''){
	global $post_product;
	$name = $name ? $name : $array['name'];
	$info = $array['infor'] ? '<span id="' . $name . '" class="cur1 mtn">&nbsp;<img src="' . IMGDIR . '/info_small.gif" alt="" /></span>' : '';
	$type = $array['type'] == 'textarea' ? 'textarea' : 'input';
	$value = $post_product['extra'][$name][0] ? $post_product['extra'][$name][0] : implode(", ", $array['value']);
	$html = '<tr><td with=130px class="title_field tdextra tdextra_1">' . $array[name] . ': ' . $info . '</td><td colspan="2" class="tdextra tdextra_2">';

	if ($type == 'input')
		$html .= '<input tabindex="1" class="ext_input" type="text" name="extra[' . $name . '][]" value="' . $value . '" id="extra_' . $name . '" />';
	else
		$html .= '<textarea tabindex="1" class="textarea_input" name="extra[' . $name . '][]" id="extra_' . $name . '">' . $value . '</textarea>';

	$html .= '<input type="hidden" name="extra[' . $name . '][name]" value="' . $array[name] . '" /></td>';
	if ($info){
		$html .= '<script>showPrompt(\'' . $name . '\', \'mouseover\', \'' . $array['infor'] . '\', 1);</script>';
	}
	$html .= '</tr>';
	return $html;
}

function param_out_is_checkbox($array, $name = ''){
	global $post_product;
	$name = $name ? $name : $array['name'];
	$type = $array['type'] == 'select' ? 'radio' : 'checkbox';
	$info = $array['infor'] ? '<span id="' . $name . '" class="cur1 mtn">&nbsp;<img src="' . IMGDIR . '/info_small.gif" alt="" /></span>' : '';
	$html = '<tr><td  with=130px class="title_field tdextra tdextra_1">' . $array[name] . ': ' . $info . '</td><td class="tdextra tdextra_2"><ul>';
	foreach ($array['value'] as $key=>$value){
		$value = trim($value);
		$checked = in_array($value, $post_product['extra'][$name]) ? 'checked="checked"' : '';
		$html .= '<li><input tabindex="1" name="extra[' . $name . '][]" type="' . $type . '" value="' . $value . '" id="extra_' . $name . $key . '" ' . $checked . ' /><label for="extra_' . $name . $key . '">' . $value . '</label></li>';
	}

	$html .= '<input type="hidden" name="extra[' . $name . '][name]" value="' . $array[name] . '" /></td>';

	if ($array['extra']){
		$html .= '<td class="tdextra tdextra_3">&nbsp- ' . lang('shop/template', 'hoac_dien') . ':&nbsp<input type="text" tabindex="1" name="extra[' . $name . '][custom]" value="' . $post_product['extra'][$name]['custom'] . '"></td>';
	}else{
		$html .= '<td class="tdextra tdextra_3"></td>';
	}

	if ($info){
		$html .= '<script>showPrompt(\'' . $name . '\', \'mouseover\', \'' . $array['infor'] . '\', 1);</script>';
	}

	$html .= '</tr>';

	return $html;
}

function param_out_is_droplist($array, $name = ''){
	global $post_product;
	$name = $name ? $name : $array['name'];
	$info = $array['infor'] ? '<span id="' . $name . '" class="cur1 mtn">&nbsp;<img src="' . IMGDIR . '/info_small.gif" alt="" /></span>' : '';
	$html = '<tr><td  with=130px class="title_field tdextra tdextra_1">' . $array[name] . ': ' . $info . '</td><td class="tdextra tdextra_2">';
	if ($array['type'] == 'droplist'){
		$html .= '<select tabindex="1" name="extra[' . $name . '][]">';
	}else{
		$html .= '<select tabindex="1"  multiple="multiple" size="7" name="extra[' . $name . '][]">';
	}

	foreach ($array['value'] as $key=>$value){
		$value = trim($value);
		$selected = in_array($value, $post_product['extra'][$name]) ? 'selected="selected"' : '';
		$html .= '<option value="' . $value . '" ' . $selected . '>' . $value . '</option>';
	}
	$html .= '</select><input type="hidden" name="extra[' . $name . '][name]" value="' . $array[name] . '" /></td>';

	if ($array['extra']){
		$html .= '<td class="tdextra tdextra_3">&nbsp- ' . lang('shop/template', 'hoac_dien') . ':&nbsp<input tabindex="1" type="text" name="extra[' . $name . '][custom]" value="' . $post_product['extra'][$name]['custom'] . '"></td>';
	}else{
		$html .= '<td class="tdextra tdextra_3"></td>';
	}

	if ($info){
		$html .= '<script>showPrompt(\'' . $name . '\', \'mouseover\', \'' . $array['infor'] . '\', 1);</script>';
	}

	$html .= '</tr>';

	return $html;
}

function shopcode($username){
	return strtoupper(substr($username, 0, 2) . substr(md5($username), 0, 3));
}

/**
 * The letter o (lowercase )) and the number 0
 * have been removed, as they can be mistaken
 * for each other.
 */

function createRandomCode(){
	$chars = "abcdefghiljkmnpqrstuvwxyz123456789";
	srand((double)microtime() * 1000000);
	$i = 0;
	$pass = '';
	while ($i <= 7){
		$num = rand() % 33;
		$tmp = substr($chars, $num, 1);
		$pass = $pass . $tmp;
		$i++;
	}
	return strtoupper($pass);
}

function check_category($cid){
	$sid = DB::fetch_first("SELECT sid FROM " . DB::table("shop_category") . " WHERE sid = '" . $cid . "'");
	if ($sid['sid'] == null)
		return false;
	else
		return $sid['sid'];
}

function check_attach_unused($aid){
	$aid2 = DB::fetch(DB::query("SELECT aid FROM " . DB::table("forum_attachment_unused") . " WHERE aid='$aid' AND isimage IN ('1', '-1')"));
	return $aid2['aid'];
}
function check_attach_used($aid){
	$aid2 = DB::fetch(DB::query("SELECT aid FROM " . DB::table("shop_products_attachment") . " WHERE aid='$aid' AND isimage IN ('1', '-1')"));
	return $aid2['aid'];
}

function insert_product($data){
	$tablename = 'shop_products';
	$pid = DB::insert($tablename, $data, TRUE);
	return $pid;
}
function update_product($data, $condition){
	$tablename = 'shop_products';
	$res = DB::update($tablename, $data, $condition);
	return $res;
}

function getattachURL($attach, $thumb = true, $used = 'used'){
	global $_G;
	$URL = '';
	$folder = 'shop/';
	if ($used != 'used'){
		$folder = 'forum/';
	}
	$URL = $attach['remote'] ? $_G['setting']['ftp']['attachurl'] . $folder : $_G[setting][discuzurl] . '/' . $_G['setting']['attachurl'] . $folder;
	if ($thumb){
		$URL .= substr($attach['attachment'], 0, 10);
		$URL .= $attach['aid'] . '.thumb.jpg';
	}else{
		$URL .= $attach['attachment'];
	}
	return $URL;
}

function getattachshop_unsed($aids = ''){
	global $_G;
	require_once libfile('function/post');
	require_once libfile('function/attachment');
	$attachs = $imgattachs = array();
	$aids = $aids ? explode('|', $aids) : array();
	if ($aids){
		$aidsnew = array();
		foreach ($aids as $aid){
			if ($aid){
				$aidsnew[] = intval($aid);
			}
		}
		$aids = "aid NOT IN (" . dimplode($aidsnew) . ") AND";
	}else{
		$aids = '';
	}
	$query = DB::query("SELECT a.*, af.*
		FROM " . DB::table('forum_attachment') . " a
		LEFT JOIN " . DB::table('forum_attachment_unused') . " af USING(aid)
		WHERE $aids (af.uid='$_G[uid]' AND a.tid='0') ORDER BY a.aid DESC");

	if ($_G['shop']['attachextensions']){
		$allowext = str_replace(' ', '', strtolower($_G['shop']['attachextensions']));
		$allowext = explode(',', $allowext);
	}else{
		$allowext = '';
	}

	while ($attach = DB::fetch($query)){
		$attach['filenametitle'] = $attach['filename'];
		$attach['ext'] = strtolower(fileext($attach['filename']));
		if ($allowext && !in_array($attach['ext'], $allowext)){
			continue;
		}
		getattach_row($attach, $attachs, $imgattachs);
	}
	return array(
			'attachs'=>$attachs,
			'imgattachs'=>$imgattachs
	);
}

function move_attach($attachs, $pid, $action = 'insert', $thumbfile = FALSE, $return = FALSE){
	global $_G;
	$dir_target = 'shop/';
	$dir_src = 'forum/';

	if ($action != 'insert'){
		$dir_target = 'forum/';
		$dir_src = 'shop/';
	}

	foreach ($attachs as $value){
		$aid = $value['aid'];
		$dir_server = $value['remote'] ? $_G['setting']['ftp']['attachdir'] : $_G['setting']['attachdir'];
		$dir_img = substr($value['attachment'], 0, 10);
		if ($value['remote']){
			$dir_server = '';
		}else{
			$dir = $_G['setting']['attachdir'] . $dir_target . $dir_img;
			$filename = $_G['setting']['attachdir'] . $dir_src . $value['attachment'];
			$target_file = $_G['setting']['attachdir'] . $dir_target . $value['attachment'];
			dmkdir($dir);
		}

		if (copy($filename, $target_file)){
			if ($thumbfile && $action == 'insert'){
				$thumbname = 'shop/' . $dir_img . $aid . '.thumb.jpg';
				pcreate_thumb($target_file, $thumbname, 140, 140, 'fixwr');
				$thumbname = 'shop/' . $dir_img . $aid . '.thumb.big.jpg';
				pcreate_thumb($target_file, $thumbname, 420, 420, 'fixwr');
			}
			punlink($value, $action, $thumbfile);
			if ($action == 'insert'){
				$data = $value;
				$data['pid'] = $pid;
				DB::insert('shop_products_attachment', $data);
				DB::delete('forum_attachment', "`aid`='$aid'", 1);
				DB::delete('forum_attachment_unused', "`aid`='$aid'", 1);
			}else{
				$data2['tid'] = 0;
				$data2['pid'] = 0;
				$data2['uid'] = $value['uid'];
				$data2['tableid'] = 127;
				$data2['downloads'] = 0;
				$aids = DB::insert('forum_attachment', $data2, true);
				$data['aid'] = $aids;
				$data['uid'] = $value['uid'];
				$data['dateline'] = $value['dateline'];
				$data['filename'] = $value['filename'];
				$data['filesize'] = $value['filesize'];
				$data['attachment'] = $value['attachment'];
				$data['remote'] = $value['remote'];
				$data['isimage'] = $value['isimage'];
				$data['width'] = $value['width'];
				$data['thumb'] = $value['thumb'];

				DB::insert('forum_attachment_unused', $data);

				DB::delete('shop_products_attachment', "`aid`='$aid'", 1);
			}
		}
	}
	if ($return){
		return $aids;
	}
}

function pcreate_thumb($filesrc, $filename, $w = 140, $h = 140, $type = 'fixwr'){
	require_once libfile('class/image');
	$img = new image();
	$img->Thumb($filesrc, $filename, $w, $h, $type);
}

function remove_attach($pid, $action = 'delete'){

	$query = DB::query("SELECT * FROM " . DB::table("shop_products_attachment") . " WHERE `pid`='$pid'");
	while ($attach = DB::fetch($query)){
		punlink($attach, $action, true);
	}
	DB::delete('shop_products_attachment', "`pid`='$pid'");
}
function punlink($attach, $action = 'insert', $thumb = FALSE){
	global $_G;
	$filename = $attach['attachment'];
	$havethumb = $attach['thumb'];
	$remote = $attach['remote'];
	$dir_src = $action == 'insert' ? '/forum/' : '/shop/';
	if ($remote){
		ftpcmd('delete', $_G['setting']['ftp']['attachdir'] . $dir_src . $filename);
		$havethumb && ftpcmd('delete', $_G['setting']['ftp']['attachdir'] . $dir_src . getimgthumbname($filename));
	}else{
		@unlink($_G['setting']['attachdir'] . $dir_src . $filename);
		$havethumb && @unlink($_G['setting']['attachdir'] . $dir_src . getimgthumbname($filename));
	}
	if ($attach['aid']){
		@unlink($_G['setting']['attachdir'] . 'image/' . $attach['aid'] . '_140_140.jpg');
	}
	if ($thumb){
		@unlink($_G['setting']['attachdir'] . $dir_src . substr($attach['attachment'], 0, 10) . '/' . $attach['aid'] . ".thumb.jpg");
		@unlink($_G['setting']['attachdir'] . $dir_src . substr($attach['attachment'], 0, 10) . '/' . $attach['aid'] . ".thumb.big.jpg");
	}
}

function delete_product($pid, $byUser){
	global $_G;
	remove_attach($pid);
	if ($byUser['uid'] != $_G['uid']){
		$note_type = 'deleteproduct';
		$note = 'delete_product';
		$note_values['url'] = "home.php?mod=space&username=" . $byUser['username'] . "&do=shopping";
		$note_values['subject'] = $byUser['pname'];
		$note_values['actor'] = $_G['username'];
		notification_add($byUser['uid'], $note_type, $note, $note_values);
	}
	return DB::delete('shop_products', "`pid`='$pid'");
}

function showmessageshopnoperm($type, $sid, $formula = ''){
	global $_G;
	loadcache('usergroups');
	if ($formula){
		$formula = unserialize($formula);
		$permmessage = stripslashes($formula['message']);
	}

	$usergroups = $nopermgroup = $forumnoperms = array();
	$nopermdefault = array(
			'viewperm'=>array(),
			'getattachperm'=>array(),
			'postperm'=>array(
					7
			),
			'replyperm'=>array(
					7
			),
			'postattachperm'=>array(
					7
			)
	);
	$perms = array(
			'viewperm',
			'postperm',
			'replyperm',
			'getattachperm',
			'postattachperm'
	);

	foreach ($_G['cache']['usergroups'] as $gid=>$usergroup){
		$usergroups[$gid] = $usergroup['type'];
		$grouptype = $usergroup['type'] == 'member' ? 0 : 1;
		$nopermgroup[$grouptype][] = $gid;
	}
	if ($sid == $_G['shop']['sid']){
		$shop = $_G['shop'];
	}else{
		$shop = DB::fetch_first("SELECT * FROM " . DB::table('shop_shopfield') . " WHERE fid='$sid'");
	}

	foreach ($perms as $perm){
		$permgroups = explode("\t", $shop[$perm]);
		$membertype = $shop[$perm] ? array_intersect($nopermgroup[0], $permgroups) : TRUE;
		$shopnoperm = $shop[$perm] ? array_diff(array_keys($usergroups), $permgroups) : $nopermdefault[$perm];
		foreach ($shopnoperm as $groupid){
			$nopermtype = $membertype && $groupid == 7 ? 'login' : ($usergroups[$groupid] == 'system' || $usergroups[$groupid] == 'special' ? 'none' : ($membertype ? 'upgrade' : 'none'));
			$shopnoperm[$sid][$perm][$groupid] = array(
					$nopermtype,
					$permgroups
			);
		}
	}

	$v = $shopnoperm[$sid][$type][$_G['groupid']][0];
	$gids = $shopnoperm[$sid][$type][$_G['groupid']][1];
	$comma = $permgroups = '';
	if (is_array($gids)){
		foreach ($gids as $gid){
			if ($gid && $_G['cache']['usergroups'][$gid]){
				$permgroups .= $comma . $_G['cache']['usergroups'][$gid]['grouptitle'];
				$comma = ', ';
			}elseif ($_G['setting']['verify']['enabled'] && substr($gid, 0, 1) == 'v'){
				$vid = substr($gid, 1);
				$permgroups .= $comma . $_G['setting']['verify'][$vid]['title'];
				$comma = ', ';
			}

		}
	}

	$custom = 0;
	if ($permmessage){
		$message = $permmessage;
		$custom = 1;
	}else{
		if ($v){
			$message = $type . '_' . $v . '_nopermission';
		}else{
			$message = 'group_nopermission';
		}
	}

	showmessage($message, NULL, array(
			'sid'=>$sid,
			'permgroups'=>$permgroups,
			'grouptitle'=>$_G['group']['grouptitle']
	), array(
			'login'=>1
	), $custom);
}

function get_str_nohtml($string){
	if (is_array($string)){
		foreach ($string as $key=>$val){
			$string[$key] = get_str_nohtml($val);
		}
	}else{
		$string = trim(str_replace(array(
				"'",
				'"',
				'<',
				'>',
				'\t'
		), array(
				'&rsquo;',
				'&quot;',
				'&lt;',
				'&gt;',
				' '
		), $string));
	}
	return pdstripcslashes($string);
}

function pdstripcslashes($string){
	if (is_array($string)){
		foreach ($string as $key=>$val){
			$string[$key] = pdstripcslashes($val);
		}
	}else{
		$string = stripcslashes($string);
	}
	return $string;
}

/*
 * Search products for attribude
 * @author mr.Trieu
 * */
function attrArray($str = ''){
	$arrays = array();
	$nArray = array();

	// $str to array()
	if (substr($str, strlen($str) - 1, 1) == chr(64))
		$str = substr($str, 0, strlen($str) - 1);

	$param = explode(chr(64), $str);
	//	$total_attr = count($param);


	foreach ($param as $value){
		$n_array = explode(chr(124), $value);
		foreach ($n_array as $value2){
			$arrays[$n_array[0]][] = $value2;
		}
	}

	foreach ($arrays as $value){
		$value = array_unique($value);
		$nArray[] = implode(chr(124), $value);
	}

	return $nArray;
}

/*
 * San pham cua woo_shop
 * @author mr.Trieu
 * */
function wooProducts($uname = '', $limit = 1){
	global $_G;
	$products = array();
	$condition = ' AND (p.pprice > 2000 OR p.uid = ' . $_G[uid] . ')';

	if ($_G['adminid'] != 1)
		$condition .= ' AND available = 1';

	$Qry = 'SELECT p.pid, p.pname, p.img_cover, a.attachment, p.pprice, p.sales, p.total_vote, p.vote, p.view, p.lastupdate
			FROM ' . DB::table("shop_products") . ' p
			LEFT JOIN ' . DB::table("shop_products_attachment") . ' a ON (p.img_cover = a.aid)
			WHERE available = 1 AND p.username = \'' . $uname . '\'' . $condition . '
			ORDER BY RAND()
			LIMIT 0,' . $limit;
	//echo $Qry;
	$res = DB::query($Qry);

	while ($row = DB::fetch($res)){
		$row['imgcoverthumb'] = ($row['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . substr($row['attachment'], 0, 10) . $row['img_cover'] . '.thumb.jpg';

		if ($row['sales']){
			$row['end_price'] = ($row['pprice'] - (doubleval($row['pprice']) * doubleval($row['sales'])) / 100);
			$row['end_price'] = FormatNumber($row['end_price']);
			$row['sales'] = FormatNumber($row['sales'], 2, '.', ",", FALSE);
		}else
			$row['end_price'] = FormatNumber($row['pprice']);

		// Rate products
		$row['point'] = $row['total_vote'] / $row['vote'];
		$row['point'] = round($row['point']);

		if ($row['view'] > 1000)
			$row['hits'] = round($row['view'] / 1000) . 'k';
		elseif ($row['view'] > 10000)
			$row['hits'] = round($row['view'] / 10000) . 'k';
		elseif ($row['view'] > 100000)
			$row['hits'] = round($row['view'] / 100000) . 'k';
		else
			$row['hits'] = $row['view'];

		$products[] = $row;
	}

	return $products;
}

/*
 * San pham khuyen mai
 * @author mr.Trieu
 * */
function proDiscount($limit = 4){
	global $_G;
	$products = array();
	$condition = ' AND (p.pprice > 2000 OR p.uid = ' . $_G[uid] . ')';

	if ($_G['adminid'] != 1)
		$condition .= ' AND available = 1';

	$Qry = 'SELECT p.pid, p.pname, p.img_cover, a.attachment, p.pprice, p.sales, p.total_vote, p.vote
			FROM ' . DB::table("shop_products") . ' p
			LEFT JOIN ' . DB::table("shop_products_attachment") . ' a ON (p.img_cover = a.aid)
			WHERE p.sales > 0' . $condition . '
			ORDER BY p.sales DESC, p.lastupdate  DESC
			LIMIT 0,' . $limit;

	$res = DB::query($Qry);

	while ($row = DB::fetch($res)){
		$row['imgcover'] = ($row['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . $row['attachment'];
		$row['imgcoverthumb'] = ($row['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . substr($row['attachment'], 0, 10) . $row['img_cover'] . '.thumb.jpg';

		if ($row['sales']){
			$row['end_price'] = ($row['pprice'] - (doubleval($row['pprice']) * doubleval($row['sales'])) / 100);
			$row['end_price'] = FormatNumber($row['end_price']);
			$row['sales'] = FormatNumber($row['sales'], 2, '.', ",", FALSE);
		}else
			$row['end_price'] = FormatNumber($row['pprice']);

		// Rate products
		$row['point'] = $row['total_vote'] / $row['vote'];
		$row['point'] = round($row['point']);

		// Danh sach hinh anh
		$row['pics'] = imgProduct($row['pid'], $row['attachment']);

		$products[] = $row;
	}

	return $products;
}

/*
 * San pham moi cap nhat
 * @author mr.Trieu
 * */
function newProducts($limit = 30){
	global $_G;
	$products = array();
	$condition = '(p.pprice > 2000 OR p.uid = ' . $_G[uid] . ')';

	if ($_G['adminid'] != 1)
		$condition .= ' AND available = 1';

	$Qry = 'SELECT p.pid, p.pname, p.img_cover, a.attachment, p.pprice, p.sales, p.total_vote, p.vote, p.view, p.lastupdate, p.username, p.status, m.*
			FROM ' . DB::table("shop_products") . ' p
			LEFT JOIN ' . DB::table("shop_products_attachment") . ' a ON (p.img_cover = a.aid)
			LEFT JOIN ' . DB::table("shop_profile") . ' m ON p.uid = m.uid
			WHERE ' . $condition . '
			ORDER BY p.lastupdate  DESC
			LIMIT 0,' . $limit;
	//echo $Qry;
	$res = DB::query($Qry);

	while ($row = DB::fetch($res)){
		$row['imgcover'] = ($row['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . $row['attachment'];
		$row['imgcoverthumb'] = ($row['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . substr($row['attachment'], 0, 10) . $row['img_cover'] . '.thumb.jpg';

		if ($row['sales']){
			$row['end_price'] = ($row['pprice'] - (doubleval($row['pprice']) * doubleval($row['sales'])) / 100);
			$row['end_price'] = FormatNumber($row['end_price']);
			$row['sales'] = FormatNumber($row['sales'], 2, '.', ",", FALSE);
		}else
			$row['end_price'] = FormatNumber($row['pprice']);

		// Rate products
		$row['point'] = $row['total_vote'] / $row['vote'];
		$row['point'] = round($row['point']);

		if ($row['view'] > 1000)
			$row['hits'] = round($row['view'] / 1000) . 'k';
		elseif ($row['view'] > 10000)
			$row['hits'] = round($row['view'] / 10000) . 'k';
		elseif ($row['view'] > 100000)
			$row['hits'] = round($row['view'] / 100000) . 'k';
		else
			$row['hits'] = $row['view'];

		$row['items'] = shopItems($row['uid']);
		// Danh sach hinh anh
		$row['pics'] = imgProduct($row['pid'], $row['attachment']);

		$products[] = $row;
	}

	return $products;
}

/*
 * Tong so san pham cua 1 shop
 * */
function shopItems($sid){
	global $_G;
	$condition = '(pprice > 2000 OR uid = ' . $_G[uid] . ')';

	if ($_G['adminid'] != 1)
		$condition .= ' AND available = 1';

	$total = DB::result_first("SELECT COUNT(*)
								FROM " . DB::table("shop_products") . "
								WHERE " . $condition . " AND uid = " . $sid);

	if ($total > 1000)
		return round($total / 1000) . 'k';
	elseif ($total > 10000)
		return round($total / 10000) . 'k';
	elseif ($total > 100000)
		return round($total / 100000) . 'k';
	else
		return $total;

}

/*
 * Lay tat cac hinh anh cua san pham
 * theo pid trong table shop_products_attachment
 * */

function imgProduct($pid, $imgCover = ''){
	global $_G;

	if (!$pid)
		return false;

	$imgs = array();

	if ($imgCover)
		$mysql = ' AND attachment != \'' . $imgCover . '\'';
	else
		$mysql = '';

	$Qry = ("SELECT attachment
			FROM " . DB::table('shop_products_attachment') . "
			WHERE pid = " . $pid . $mysql . "
			ORDER BY dateline ASC");
	//echo $Qry . '<br />';
	$res = DB::query($Qry);

	while ($row = DB::fetch($res)){
		$imgs[] = ($row['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . $row['attachment'];
	}

	return $imgs;
}

/*
 * Get province for Vietnam
 * */
function provice($upid = 45052){

	$location_country[] = array(
			'id'=>'0',
			'name'=>lang('shop/country', 'Tat_ca_tinh_thanh'),
			'level'=>'0',
			'upid'=>'45052',
			'displayorder'=>'0'
	);

	$query = DB::query("SELECT id, name
						FROM " . DB::table('common_district') . "
						WHERE level = 2 AND upid = 45052
						ORDER BY name ASC");

	while ($result = DB::fetch($query)){
		$result['url'] = '&province=' . $result['id'];
		$location_country[] = $result;
	}

	return $location_country;
}
/*
 * For memcached
 * */
function get_memory_cached($key){
	if (memory('check')){
		$set = memory('get', $key);
		define($key, $set ? 1 : 0);
		if ($set){
			return $set;
		}
	}
	return array(
			'none'=>null
	);
}
?>